package com.easylinkin.linkappapi.alarm.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.alarm.entity.Alarm;
import com.easylinkin.linkappapi.alarm.entity.AlarmNotice;
import com.easylinkin.linkappapi.alarm.mapper.AlarmNoticeMapper;
import com.easylinkin.linkappapi.alarm.service.AlarmNoticeService;
import com.easylinkin.linkappapi.common.utils.message.SendEmailUtil;
import com.easylinkin.linkappapi.common.utils.message.SendMessageUtil;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.messagecenter.entity.MessageCenterDetail;
import com.easylinkin.linkappapi.messagecenter.entity.vo.MessageCenterVo;
import com.easylinkin.linkappapi.messagecenter.service.MessageCenterService;
import com.easylinkin.linkappapi.security.constant.LinkappUserConstant;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 告警通知日志 服务实现类
 * </p>
 *
 * @author TongJie
 * @since 2020-05-14
 */
@Service
public class AlarmNoticeServiceImpl extends ServiceImpl<AlarmNoticeMapper, AlarmNotice> implements AlarmNoticeService {

    public static final Integer PHONE_TYPE = 1;
    public static final Integer EMAIL_TYPE = 2;
    public static final Integer PHONE_AND_EMAIL_TYPE = 3;

    public static final Integer CENTER_MESSAGE_TYPE = 4;

    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;
    @Lazy
    @Autowired
    private SendEmailUtil sendEmailUtil;
    @Lazy
    @Autowired
    private SendMessageUtil sendMessageUtil;

    @Lazy
    @Autowired
    private MessageCenterService messageCenterService;

    @Lazy
    @Autowired
    private AlarmNoticeService alarmNoticeService;

    @Override
    public IPage<AlarmNotice> getAlarmNoticePage(Page page, AlarmNotice alarmNotice) {
        //  普通账户，只能看到 通知自己的 告警通知，管理员可以看到所有人的通知；
        // 普通账户，通知的下拉列表 只有自己， 管理员的下拉列表有所有人
        LinkappUser currentUser = linkappUserContextProducer.getCurrent();
        LinkappUser user = alarmNotice.getLinkappUser();
        if (!LinkappUserConstant.ADMIN_TYPE.equals(currentUser.getType())) {
            alarmNotice.setLinkappUser(currentUser);
        } else {
            if (user == null || user.getId() == null) {
                alarmNotice.setLinkappUser(null);
            }
        }
        return baseMapper.getAlarmNotices(page, alarmNotice);
    }

    @Override
    public List<AlarmNotice> getAlarmNotices(AlarmNotice alarmNotice) {
        //  普通账户，只能看到 通知自己的 告警通知，管理员可以看到所有人的通知；
        // 普通账户，通知的下拉列表 只有自己， 管理员的下拉列表有所有人
        LinkappUser currentUser = linkappUserContextProducer.getCurrent();
        LinkappUser user = alarmNotice.getLinkappUser();
        if (!LinkappUserConstant.ADMIN_TYPE.equals(currentUser.getType())) {
            alarmNotice.setLinkappUser(currentUser);
        } else {
            if (user == null || user.getId() == null) {
                alarmNotice.setLinkappUser(null);
            }
        }
        return baseMapper.getAlarmNotices(alarmNotice);
    }

    @Override
    public List<LinkappUser> getNoticeUser(AlarmNotice requestModel) {
        requestModel.setLinkappUser(linkappUserContextProducer.getCurrent());
        return baseMapper.getNoticeUser(requestModel);
    }

    @Override
    public void noticeAndSaveAlarmNotices(List<AlarmNotice> alarmNotices, Device device, Alarm alarm) {
        if (CollectionUtils.isEmpty(alarmNotices)) {
            return;
        }
        List<AlarmNotice> alarmNoticesCopys = new ArrayList<>();
        for (AlarmNotice alarmNotice : alarmNotices) {
            AlarmNotice alarmNoticesCopy = new AlarmNotice();
            BeanUtils.copyProperties(alarmNotice, alarmNoticesCopy);
            alarmNoticesCopys.add(alarmNoticesCopy);
            //20220819变更，不发邮件、短信,变更未发送内部平台消息
            //在这里增加产生消息中心数据的机制
            alarmNotice.setId(null);
            alarmNotice.setSendTime(DateUtil.date());
            alarmNotice.setMessageType(AlarmNoticeServiceImpl.CENTER_MESSAGE_TYPE); //信息中心信息
            alarmNotice.setMessageWay(AlarmNoticeServiceImpl.CENTER_MESSAGE_TYPE.toString());
            alarmNoticeService.save(alarmNotice);
            MessageCenterVo msgVo = alarmNoticeToCenterMsgVo(alarmNotice,device,alarm);
            messageCenterService.makeMessageCenterMsg(msgVo);
        }
        //20220819变更，不发邮件、短信,变更未发送内部平台消息
        //sendMessageUtil.sendSmsAndSaveAlarmNotice(alarmNotices);
        //sendEmailUtil.sendEmailAndSaveAlarmNotice(alarmNoticesCopys);

    }

    /**
     * 设备告警通知转消息中心信息
     *
     * @param alarmNotice 告警通知
     * @param device
     * @param alarm
     * @return 消息中心信息
     */
    private MessageCenterVo alarmNoticeToCenterMsgVo(AlarmNotice alarmNotice, Device device, Alarm alarm) {
        MessageCenterVo messageCenter = new MessageCenterVo();
        messageCenter.setType(3);
        messageCenter.setTenantId(alarmNotice.getTenantId());
        messageCenter.setCreateTime(DateUtil.date());
        messageCenter.setModifyTime(messageCenter.getCreateTime());
        messageCenter.setStatus(0);
        //messageCenter.setContent(alarmNotice.getContent());
        messageCenter.setContent(alarmNotice.getDeviceName() + " " + alarmNotice.getContent());
        messageCenter.setTitle(alarmNotice.getRuleEngineName());
        //直接设置属于所有用户，（有模块权限就可以看到）
        messageCenter.setOwnerId(alarmNotice.getUserId());
        //跟报警记录关联
        messageCenter.setLinkId(alarm.getId());

        //详情
        MessageCenterDetail detail = new MessageCenterDetail();
        detail.setDeviceCode(device.getCode());
        detail.setPosition(alarmNotice.getAreaPath());
        detail.setDeviceTypeName(alarmNotice.getDeviceType());
        detail.setTenantId(messageCenter.getTenantId());
        //并不是所有设备都有负责人，表结构做了限制，个人觉得应该业务上做这样的限制。消息中心的设计高度可以提高下
        detail.setLeadId("-1");

        List<MessageCenterDetail> detailLs = new ArrayList<>();
        detailLs.add(detail);

        messageCenter.setMessageCenterDetailList(detailLs);

        return messageCenter;
    }


}